<?php

namespace plugins\yongtai\controller;

use plugins\yongtai\controller\Base\AdminBaseController;

class UploadController extends AdminBaseController
{
    public $max_size = 2000000;
    public $file_type_list = ["image/gif", "image/jpeg", "image/png"];

    private function VerifyFileType($file_type)
    {
        return in_array($file_type, $this->file_type_list);
    }

    private function UploadFile($file, $has_image_postfix_url = true, $filename = "upload/default/")
    {
        if ($this->VerifyFileType($file['type']) && ($file["size"] < $this->max_size)) {
            if ($file["error"] > 0) {
                return "Return Code: " . $file["error"] . "<br />";
            } else {
                $path = $filename . date('Ymd', time()) . '/';
                $arr = explode('.', $file["name"]);
                $profix = $arr[count($arr) - 1];
                $_filename = md5($file["name"]) . '.' . $profix;
                $image_postfix_url = $this->image_postfix_url;
                if (file_exists($path . $_filename)) {
                    $__url = 'default/' . date('Ymd', time()) . '/' . $_filename;
                    return $has_image_postfix_url ? $image_postfix_url . $__url : $__url;
                } else {
                    if (!file_exists($path)) {
                        mkdir($path, 0741, true);
                    }
                    move_uploaded_file($file["tmp_name"], $path . $_filename);
                    $__url = 'default/' . date('Ymd', time()) . '/' . $_filename;
                    return $has_image_postfix_url ? $image_postfix_url . $__url : $__url;
                }
            }
        } else {
            return false;
        }
    }

    function OneImage()
    {
        $file = $_FILES["file"];
        $res = $this->UploadFile($file, false);
        if ($res) {
            $res = [
//                'code' => 1,
                "location" => $this->image_postfix_url . $res,
                "url" => $res,
            ];
            return json($res);
        } else {
            $this->error("Invalid file");
        }
    }

    function MultipleImage()
    {
        $list = [];
        $files = $_FILES['files'];
        for ($i = 0; $i < count($files['name']); $i++) {
            $file = [
                'name' => $files['name'][$i],
                'type' => $files['type'][$i],
                'size' => $files['size'][$i],
                'error' => $files['error'][$i],
                'tmp_name' => $files['tmp_name'][$i],
            ];
            $list[] = $this->UploadFile($file);
        }
        $this->success($list);
    }
}
